package com.seeyon.apps.kksso.controller;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.kksso.common.UserCoderUtil;
import com.seeyon.apps.kksso.common.createUrl;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.service.NeedlessCheckLoginAnnotationAware;
import com.seeyon.ctp.organization.bo.V3xOrgEntity;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.annotation.Inject;
import org.apache.commons.logging.Log;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class loginController extends BaseController {
    private final Log log = CtpLogFactory.getLog(this.getClass());
    public static String oaUrl = AppContext.getSystemProperty("kksso.oaHost");
    @Inject
    private OrgManager orgManager;
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        createUrl createUrl = new createUrl();
        String loginUrl = createUrl.makeLoginUrl();
        log.info("重定向到统一认证loginUrl:"+loginUrl);
        response.sendRedirect(loginUrl);
        return null;
    }
    /**
     * 回调接口
     */
    public void loginSso(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("单点登录开始");
        String userId="";
        String code = request.getParameter("code");
        // 单点
        String token = new createUrl().getToken(code);
        if (token!=null){
            JSONObject jsonObject = JSONObject.parseObject(token);
            String accessToken = (String) jsonObject.get("access_token");
            log.info("获取用户的accessToken:"+accessToken);
            String userInfo = new createUrl().getUserInfo(accessToken);
            jsonObject = JSONObject.parseObject(userInfo);
            log.info("获取用户信息"+ jsonObject);
            userId = (String) jsonObject.get("id");
        }
        Long memberId = queryUserMemberIdByUserCode(userId);


        V3xOrgMember member = orgManager.getMemberById(memberId);
        if (member!=null){
            log.info("登录人LoginName:"+member.getLoginName());
            String loginName = member.getLoginName();
            log.info("loginName:"+loginName);
            String redirectUrl = "";
//                    String strUserName = loginName + "-" + UUID.randomUUID().toString().replace("-", "");
            String strUserName = UserCoderUtil.encrypt(loginName);
            log.info("strUserName:"+strUserName);
            redirectUrl = oaUrl+"/seeyon/login/sso?from=oasso&ticket="+strUserName;
            log.info("重定向url:"+redirectUrl);
            response.sendRedirect(redirectUrl);
        }
    }

    /**
     * 单点登录白名单
     * @throws BusinessException
     */
    public void noAuthenticationInit() throws BusinessException {
        log.info("单点登录免认证---开始");
        NeedlessCheckLoginAnnotationAware needless = (NeedlessCheckLoginAnnotationAware) AppContext.getBean("NeedlessCheckLoginAnnotationAware");
        if (null != needless) {
            Set<String> m = new HashSet<String>();
            m.add("loginSso");
            needless.getNeedlessUrlMap().put("/loginController.do", m);
            super.needlessUrlMap.put("/loginController.do", m);
            super.needlessClassMap.put(this.getClass().getName(), m);

            log.info("单点登录免认证---结束");
        } else {
            log.info("单点登录免认证---异常");
            throw new BusinessException("Failed to initialize NeedlessCheckLogin method");
        }
    }
    public Long queryUserMemberIdByUserCode(String userCode) throws BusinessException {
        Long result = 0L;
        try {
            List<V3xOrgEntity> code = orgManager.getEntityNoRelation(V3xOrgMember.class.getSimpleName(), "code", userCode, null, false, true, null);
            if (code != null && code.size() > 0) {
                result = code.get(0).getId();
            }
        }catch (BusinessException e){
            throw new BusinessException(e);
        }
        return result;
    }

}
